package com.roc.web.action.merinfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.MerinfoSearchBean;
import com.roc.bean.orgMainBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblEditMchtBizFee;
import com.roc.pojo.TblEditMchtInf;
import com.roc.pojo.TblInsInf;
import com.roc.service.IMerchantServices;
import com.roc.service.IorgService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;

@Component
@Namespace("/merTempSave")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class merinfoTempSaveAction extends PaginationBaseAction {
	static Logger logger = Logger.getLogger(merinfoTempSaveAction.class);
	
	@Autowired
	IPageService pageService;
	@Autowired
	IMerchantServices merinfoService;
	private MerinfoTempSaveSearchCondtion searchCondition;
	private TblEditMchtInf merinfo;
	private String provice32;//省份32域名
	private String city32;//城市32域
	private Double zwPayRate;
	private String saveTmpMerinfoFlag;
	@Autowired
	IorgService orgService;
	@Autowired
	IPowerInfoService powerInfoService;
	
	@Action(value = "merinfoTempSaveList", results = {	
			@Result(name =SUCCESS, location = "/pages/merinfo/merinfoTempSaveList.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String merinfoTempSaveList(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition == null ){
				searchCondition = (MerinfoTempSaveSearchCondtion) getSearchConditionFromSession();
				if(searchCondition == null){
					searchCondition = new MerinfoTempSaveSearchCondtion();
				}
			}
			searchCondition.setOperId(String.valueOf(op.getId()));
			handleTmpSaveResultList(op);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	public void handleTmpSaveResultList(Operators op) throws Exception{
		try {
			int rows = pageService.countSQL(searchCondition);
			List<MerinfoSearchBean> msList= new ArrayList<MerinfoSearchBean>();
			if(rows > 0){
				searchRsList = pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()),Constance.PAGE_MAX_SIZE);
				if(searchRsList.size()>0 && searchRsList != null){
					msList = handleDetailForMerTmp(searchRsList, op);
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("COUNT", rows);
			getRequest().setAttribute(SEARCH_RS_LIST, msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("opid", op.getId());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception("查询失败",e);
		}
	}
	
	public List<MerinfoSearchBean> handleDetailForMerTmp(List<Object> objList,Operators  op) throws Exception{
		List<MerinfoSearchBean> mList = new ArrayList<MerinfoSearchBean>();
		Iterator iterator = objList.iterator();
		while(iterator.hasNext()){
			Object[] obj = (Object[])iterator.next();
			MerinfoSearchBean msb = new MerinfoSearchBean();
			msb.setMid(Constance.Null2EmptyTrim(obj[0]));	//商户号
			msb.setMerName(Constance.Null2EmptyTrim(obj[1]));	//商户简称
			msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[2])));	//商户状态
			msb.setSetTime(Constance.Null2EmptyTrim(obj[3]));	//创建时间
			msb.setRecUpdOpr(Constance.null2Zero(obj[4])); //进件人
			mList.add(msb);
		}
		return mList;
	}
	
	// 初始化页面信息
	private void init(boolean city) throws Exception {
		try {
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);//当前操作员
			getRequest().setAttribute("opers", op.getRealName());//申请人名称
			getRequest().setAttribute("groupCd", op.getGroupCd());//申请人的直间连属性
			
			if( city==true &&null!=op.getAreaCode()&& !op.getAreaCode().equals("") &&  !op.getAreaCode().trim().equals("0000")  ){
				if(op.getAreaCode().trim().equals("3600") || op.getAreaCode().trim().equals("8500")){ //安徽和青海的省份代码
					addActionMessage("提示：安徽和青海暂停进件业务，具体详情请联系相关业务人员！");
					return;
				}
				String areaCode=ConfigMerinfoUtil.getGBProviceCodeForInsert(op.getAreaCode(),false);//地区码编码
				String provicesName=ConfigMerinfoUtil.getGBProviceCodeForInsert(op.getAreaCode(),true);//地区码名称
				getRequest().setAttribute("areaCode", areaCode);//地区码编码
				getRequest().setAttribute("proName", provicesName);//地区码名称
			}
			getRequest().setAttribute("certifType", ConfigProperties.getSysDB1("CERTIF_TYPE",true));//证件类型
			getRequest().setAttribute("posType", ConfigProperties.getSysDB1("Terminal_Type",true));//终端类型
			getRequest().setAttribute("org", op.getOrgCode());//机构
			getRequest().setAttribute("bankList", ConfigProperties.getSysDB1("UP_BC_CD",false));//银行信息
			Map<String, String> bMap = ConfigProperties.getSysDB1("UP_BC_CD",false);
			getRequest().setAttribute("bMapToList", bMap.values());//银行信息
			getRequest().setAttribute("mccMapToList", ConfigProperties.getHyMccTypeProperties().values());//mcc
			getRequest().setAttribute("roleType", op.getRoleType()); //登录人角色
			if("2".equals(op.getGroupCd()) && (Role.OPERATORS_COMM.getCode().equals(op.getRoleType()) || Role.OPERATORS_LEAD.getCode().equals(op.getRoleType()))){
				List<TblInsInf> orgList = orgService.queryAllOrgList();
				List<Operators> orgMainList = powerInfoService.queryOperatorsByParams(op.getRoleType(), op.getOneagentid());
				getRequest().setAttribute("orgList", orgList);
				getRequest().setAttribute("orgMainList", orgMainList);
			}
			Map developPersonMap= new HashMap();
			if(("10".equals(op.getRoleType())||"18".equals(op.getRoleType()) )&&"2".equals(op.getGroupCd())){
				developPersonMap=merinfoService.getOpIdsTreeBySuperId(op);
			}
			getRequest().setAttribute("developPersonMap", developPersonMap);//发展人列表
		} catch (Exception e) {
			logger.error("商户查询初始化失败", e);
			throw new Exception("商户查询初始化失败");
		}
	}
	
	/**
	 * 暂存完善信息详情
	 * @return
	 */
	@Action(value = "merTempSaveComplete",
			results = { @Result(name = SUCCESS, location = "/pages/merinfo/merTempSaveComplete.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String merTempSaveComplete(){
		try {
			init(true);
			merinfo = merinfoService.queryMerinfoTmpInfo(merinfo.getId(), false, false, true);
			merinfo.setNationCd(merinfo.getNationCd().trim());
			List<TblEditMchtBizFee> fees = merinfo.getFee();
			if(fees != null && fees.size() > 0){
				for(TblEditMchtBizFee fee : fees){
					if(fee != null){
						if(fee.getProdCd() != null && ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(fee.getProdCd())){
							zwPayRate = fee.getMchtFeePercent();
						}
					}
				}
			}
			if(merinfo.getMchtExtendInfo() != null){
				//身份证有效期长期与否判断
				if((merinfo.getMchtExtendInfo().getCertifStartDate()==null || merinfo.getMchtExtendInfo().getCertifStartDate()=="") 
						&& (merinfo.getMchtExtendInfo().getCertifEndDate()==null || merinfo.getMchtExtendInfo().getCertifEndDate()=="")){
					merinfo.getMchtExtendInfo().setCertifValidity("0");
				}else{
					merinfo.getMchtExtendInfo().setCertifValidity("1");
				}
				//营业执照有效期长期与否判断
				if((merinfo.getMchtExtendInfo().getBusiLiceStartDate()==null || merinfo.getMchtExtendInfo().getBusiLiceStartDate()=="") 
						&& (merinfo.getMchtExtendInfo().getBusiLiceEndDate()==null || merinfo.getMchtExtendInfo().getBusiLiceEndDate()=="")){
					merinfo.getMchtExtendInfo().setBusiLiceValidity("0");
				}else{
					merinfo.getMchtExtendInfo().setBusiLiceValidity("1");
				}
			}
			if(null!=merinfo.getUpMccCd()){
				getRequest().setAttribute("mccReq", ConfigMerinfoUtil.getMccByKey(merinfo.getUpMccCd()));//mcc名称
			}
				getRequest().setAttribute("provinesMap", ConfigProperties.getUnionProviceProperties());//32域省份
			if(Constant.STR_NUMBER_ONE.equals(merinfo.getGroupCD())){
				getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getDirectProductList(ConfigMerinfoUtil.DIRECT_FUNCTION_ALL, false));//获取开通直连产品信息
				getRequest().setAttribute("product", ConfigMerinfoUtil.getDirectProductTypeList()); //直连商户开通产品类型
			}else{
				getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getPosFunction(ConfigMerinfoUtil.ALL_FUNCTION, false));//开通产品信息
				getRequest().setAttribute("product", ConfigMerinfoUtil.getProductListNew());//开通产品信息
			}
			String areaProvinceCode = merinfoService.getInstalledProvince(merinfo.getUcBccd());
			String areaCityCode = merinfoService.getInstalledCity(merinfo.getUcBccd());
			getRequest().setAttribute("areaProvinceCode", areaProvinceCode);
			getRequest().setAttribute("areaCityCode", areaCityCode);
			provice32 = areaProvinceCode;
		} catch (Exception e) {
			logger.error("加载商户基本信息出错", e);
			addActionError("加载商户基本信息出错");
		}
		return SUCCESS;
	}
	
	/**
	 * 暂存完善信息提交
	 * @return
	 */
	@Action(value = "editMerTmpComplete", 
			results = { @Result(name =SUCCESS, type = "chain", location = "merinfoTempSaveList"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String editMerTmpComplete(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			String returninfo = "";
			if(Constant.STR_NUMBER_ONE.equals(saveTmpMerinfoFlag)){
				returninfo = merinfoService.editMerTempSaveInfo(merinfo, op, false);
			}else{
				if(merinfo.getProductCode()==null || merinfo.getProductCode().length<1){//未选择产品
					addActionMessage("产品信息未选择"); return SUCCESS;
				}
				if(merinfo.getProductCode().length==1 && (merinfo.getProductCode()[0]=="1171" || merinfo.getProductCode()[0]=="1271")){//只选择t0
					addActionMessage("产品信息T+1必选"); return SUCCESS;
				}
				if(merinfo.getUcBccd()==null || merinfo.getUcBccd().equals("0") || merinfo.getUcBccd().equals("")){
					merinfo.setUcBccd(provice32);//省市
				}
				returninfo = merinfoService.editMerTempSaveInfo(merinfo, op, true);
			}
			addActionMessage(returninfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()	throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_TEMP_MERINFO_INFO, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (MerinfoTempSaveSearchCondtion) getSession().getAttribute(SEARCH_SESSION_TEMP_MERINFO_INFO);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public MerinfoTempSaveSearchCondtion getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerinfoTempSaveSearchCondtion searchCondition) {
		this.searchCondition = searchCondition;
	}

	public TblEditMchtInf getMerinfo() {
		return merinfo;
	}

	public void setMerinfo(TblEditMchtInf merinfo) {
		this.merinfo = merinfo;
	}

	public String getProvice32() {
		return provice32;
	}

	public void setProvice32(String provice32) {
		this.provice32 = provice32;
	}

	public String getCity32() {
		return city32;
	}

	public void setCity32(String city32) {
		this.city32 = city32;
	}

	public Double getZwPayRate() {
		return zwPayRate;
	}

	public void setZwPayRate(Double zwPayRate) {
		this.zwPayRate = zwPayRate;
	}

	public String getSaveTmpMerinfoFlag() {
		return saveTmpMerinfoFlag;
	}

	public void setSaveTmpMerinfoFlag(String saveTmpMerinfoFlag) {
		this.saveTmpMerinfoFlag = saveTmpMerinfoFlag;
	}
	
}